<?php

namespace app\admin\controller\wanlshop;

use app\admin\library\Auth;
use app\admin\model\UserGroup;
use app\common\controller\Backend;
use app\common\library\QueueApi;
use app\index\model\wanlshop\GoodsSku;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\admin\model\wanlshop\Goods
     */
    protected $model = null;
    protected $searchFields = 'id,title';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Goods;
        $groupList = \app\admin\model\wanlshop\Shopgroup::where(['status' => 'normal'])->select();
        // 类目
        $tree = Tree::instance();
        // 1.0.2升级 过滤隐藏
        $tree->init(model('app\index\model\wanlshop\Category')->where(['type' => 'goods', 'isnav' => 1])->field('id,pid,name')->order('weigh asc,id asc')->select());
        $this->assignconfig('channelList', $tree->getTreeArray(0));
        $this->assignconfig('groupList', $groupList);
        $this->view->assign('groupList', $groupList);
        $packageRules = model('app\admin\model\wanlshop\Packagerule')->where('type','alone')->select();
        $this->assignconfig('packageRules', $packageRules);
        $this->view->assign('packageRules', $packageRules);

        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("stockList", $this->model->getStockList());
        $this->view->assign("specsList", $this->model->getSpecsList());
        $this->view->assign("distributionList", $this->model->getDistributionList());
        $this->view->assign("activityList", $this->model->getActivityList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['category','shopsort','shop','sku'=>function($query){
                        $query->where(['state' => '0']);
                    }])
                    ->where($where)
                    ->where([
                        'goods.shop_id'=>0,
                        'parent_id' => 0
                    ])
                    ->order($sort, $order)
                    ->count();
    
            $list = $this->model
                    ->with(['category','shopsort','shop','sku'=>function($query){
                        $query->where(['state' => '0']);
                    }])
                    ->where($where)
                    ->where([
                        'goods.shop_id'=>0,
                        'parent_id' => 0
                    ])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
    
            foreach ($list as $row) {
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('shopsort')->visible(['name']);
                $row->getRelation('shop')->visible(['shopname']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$val){
                $val['status'] = $val['status']=="hidden"?0:1;
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        //设置过滤方法
        $this->request->filter(['']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $single = $this->request->post('single/a');
            if ($params) {
                if(empty($params["image"]) && isset($params["images"])){
                    $images_ar = $params["images"]?explode(",",$params["images"]):[];
                    $params["image"]  = $images_ar[0]??"";
                }
                $params['exp_date'] = $params['exp_date']?:null;

                $result = false;
                Db::startTrans();
                try {
                    if($params['specs'] == 'single'){
                        // 获取自增ID
                        $data = $params;
                        $data['shop_id'] = 0;
                        $data['category_attribute'] = isset($params['attribute']) ? json_encode($params['attribute'], JSON_UNESCAPED_UNICODE) : '';
                        $data['price'] = $single['price'];

                        $data['supply_price'] = $single['supply_price'];
                        $data['market_price'] = $single['market_price'];
                        if($this->model->allowField(true)->save($data)){
                            $result = true;
                        }
                        $groupPriceArr = $single['group_price'];
                        $groupPrice = [];
                        foreach ($groupPriceArr as $key => $group){
                            $groupPrice[] = [
                                'group_id' => $key,
                                'price' => $group
                            ];
                        }

                        $sku[] = [
                            'goods_id' 		=> $this->model->id,
                            'difference' 	=> '默认',
                            'difference_en' 	=> 'default',
                            'market_price' 	=> $single['market_price'],
                            'supply_price' 	=> $single['supply_price'],
                            'group_price' 	=> json_encode($groupPrice),
                            'price' 		=> $single['price'],
                            'rule_id' 	    => $single['rule_id'],
                            'stock' 		=> 999,
                            'weigh' 		=> $single['weigh']!=''?$single['weigh'] : 0,
                            'sn' 			=> $single['sn']!=''?$single['sn'] : 'xts_'.time()
                        ];
                        $spu[] = [
                            'goods_id' => $this->model->id,
                            'name' => '规格',
                            'name_en' => 'specifications',
                            'item' => '默认',
                            'item_en' => 'default',
                        ];
                        if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                            $result == false;
                        }
                    }
                    else{
                        // 判断产品属性是否存在
                        empty($params['spuItem'])?$this->error(__('请完善：销售信息 - 产品属性')):'';
                        $spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写销售信息-产品属性'));
                        $spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写销售信息-产品属性-产品规格'));
                        // 获取自增ID
                        $data = $params;
                        $data['shop_id'] = 0;
                        $data['category_attribute'] = isset($params['attribute']) ? json_encode($params['attribute'], JSON_UNESCAPED_UNICODE) : '';
                        $data['price'] = min($params['price']);
                        $data['supply_price'] = min($params['supply_price']);
                        if($this->model->allowField(true)->save($data) !== false){
                            $result = true;
                        }
                        // 写入SPU
                        $spu = [];
                        foreach (explode(",", $spudata) as $key => $value) {
                            $value = explode('|',$value);
                            $name = $value[0] ?? '';
                            $name_en = $value[1] ?? $value[0];

                            $item = [];
                            $item_en = [];
                            foreach (explode(',',$spuItem[$key]) as $val){
                                $v         = explode('|',$val);
                                $item[]    = $v[0] ?? '';
                                $item_en[] = $v[1] ?? $v[0];
                            }
                            $spu[] = [
                                'goods_id' => $this->model->id,
                                'name'	   => $name,
                                'name_en'  => $name_en,
                                'item'     => implode(',',$item),
                                'item_en'  => implode(',',$item_en),
                            ];
                        }
                        if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                            $result == false;
                        }
                        // 写入SKU
                        $sku = [];
                        foreach ($params['sku']  as $key => $value) {
                            $difference = [];
                            $difference_en = [];
                            foreach (explode(',',$value) as $val){
                                $v = explode('|',$val);
                                $difference[] = $v[0] ?? '';
                                $difference_en[] = $v[1] ?? $v[0];
                            }
                            $sku[] = [
                                'goods_id' 		=> $this->model->id,
                                'difference' => implode(',',$difference),
                                'difference_en' => implode(',',$difference_en),
                                'market_price' 	=> $params['market_price'][$key],
                                'price' 		=> $params['price'][$key],
                                'supply_price'  => $params['supply_price'][$key],
                                'group_price'   => $params['group_price'][$key],
                                'stock' 		=> $params['stocks'][$key]??0,
                                'sort'          => $params['sort'][$key],
                                'weigh' 		=> $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
                                'sn' 			=> $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time()
                            ];
                        }
                    }

                    if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
                        $result == false;
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    throw $e;
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    throw $e;
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    throw $e;
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $shop_id = $this->shop->id;
        // 判断是否存在品牌
        $row['brand'] = model('app\index\model\wanlshop\Brand')->where(['state' => 1])->count();
        // 判断是否有店铺分类
        $row['shopsort'] = model('app\index\model\wanlshop\ShopSort')->where('shop_id',$shop_id)->count();
        // 判断是否有运费模板
        $row['freight'] = model('app\index\model\wanlshop\ShopFreight')->where('shop_id',$shop_id)->count();
        // 判断是否有寄件人信息
        $row['config'] = model('app\index\model\wanlshop\ShopConfig')->where('shop_id',$shop_id)->find();
        // 打开方式
        $this->assignconfig("isdialog", IS_DIALOG);
        $this->view->assign("row", $row);
        $this->view->assign("shop_id", $shop_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['']);
        $row = $this->model->get($ids);
        $single = $this->request->post('single/a');
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 查询SKU
        $skuItem = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $ids, 'state' => 0])
            ->field('id,difference,difference_en,price,market_price,supply_price,group_price,stock,weigh,sn,sales,state,rule_id')
            ->order('sort asc')
            ->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if(empty($params["image"]) && isset($params["images"])){
                    $images_ar = $params["images"]?explode(",",$params["images"]):[];
                    $params["image"]  = $images_ar[0]??"";
                }
                $params['exp_date'] = $params['exp_date']?:null;
                //单独修改字段不验证token
                if(count($params) == 1 && isset($params['supply_price'])){
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                }
                if(count($params) == 1 && isset($params['exp_date'])){
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    if($params['specs'] == 'single') {    //单属性
                        // 获取自增ID
                        $data = $params;
                        $data['shop_id'] = 0;
                        $data['category_attribute'] = isset($params['attribute']) ? json_encode($params['attribute'], JSON_UNESCAPED_UNICODE) : '';
                        $data['price'] = $single['price'];
                        $data['market_price'] = $single['market_price'];
                        $data['supply_price'] = $single['supply_price'];

                        if ($row->allowField(true)->save($data) !== false) {
                            $result = true;
                        }
                        $groupPriceArr = $single['group_price'];
                        $groupPrice = [];
                        foreach ($groupPriceArr as $key => $group) {
                            $groupPrice[] = [
                                'group_id' => $key,
                                'price' => $group
                            ];
                        }
                        $skuRow = model('app\index\model\wanlshop\GoodsSku')->where([
                            'goods_id' => $ids,
                            'difference' => '默认',
                        ])->order('createtime desc')->find();
                        $skuRow_id = $skuRow?$skuRow["id"]:0;
                        $sku[] = [
                            'id' => $skuRow_id,
                            'goods_id' => $row['id'],
                            'difference' => '默认',
                            'market_price' => $single['market_price'],
                            'supply_price' => $single['supply_price'],
                            'rule_id' => $single['rule_id'],
                            'group_price' => json_encode($groupPrice),
                            'price' => $single['price'],
                            'stock' => 0,
                            'weigh' => $single['weigh'] != '' ? $single['weigh'] : 0,
                            'sn' => $single['sn'] != '' ? $single['sn'] : 'xts_' . time()
                        ];
                        // 删除原来数据,重新写入SPU
                        model('app\index\model\wanlshop\GoodsSpu')
                            ->where('goods_id', 'in', $ids)
                            ->delete();
                        $spu[] = [
                            'goods_id' => $ids,
                            'name' => '规格',
                            'name_en' => 'specifications',
                            'item' => '默认',
                            'item_en' => 'default',
                        ];
                        if (!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)) {
                            $result == false;
                        }

                    }else{   //多属性
                        // 判断产品属性是否存在
                        empty($params['spuItem'])?$this->error(__('请完善：销售信息 - 产品属性')):'';
                        $spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写销售信息-产品属性'));
                        $spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写销售信息-产品属性-产品规格'));
                        // 写入表单
                        $data = $params;
                        if(isset($data['attribute'])){
                            $data['category_attribute'] = json_encode($data['attribute'], JSON_UNESCAPED_UNICODE);
                        }
                        $data['price'] = min($data['price']);
                        $data['supply_price'] = min($params['supply_price']);
                        $result = $row->allowField(true)->save($data);
                        // 删除原来数据,重新写入SPU
                        model('app\index\model\wanlshop\GoodsSpu')
                            ->where('goods_id','in',$ids)
                            ->delete();
                        $spu = [];
                        foreach (explode(",", $spudata) as $key => $value) {

                            $value = explode('|',$value);
                            $name = $value[0] ?? '';
                            $name_en = $value[1] ?? $value[0];

                            $item = [];
                            $item_en = [];
                            foreach (explode(',',$spuItem[$key]) as $val){
                                $v = explode('|',$val);
                                $item[] = $v[0] ?? '';
                                $item_en[] = $v[1] ?? $v[0];
                            }
                            $spu[] = [
                                'goods_id' => $ids,
                                'name' => $name,
                                'name_en' => $name_en,
                                'item' => implode(',',$item),
                                'item_en' => implode(',',$item_en),
                            ];
                        }

                        if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                            $result == false;
                        }
                        //标记旧版SKU数据
                        $oldsku = [];
                        foreach ($skuItem as $value) {
                            $oldsku[] = [
                                'id' => $value['id'],
                                'state' => 1
                            ];
                        }
                        if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($oldsku)){
                            $result == false;
                        }
                        // 写入SKU
                        $sku = [];
                        foreach ($params['sku'] as $key => $value) {

                            $difference = [];
                            $difference_en = [];
                            foreach (explode(',',$value) as $val){
                                $v = explode('|',$val);
                                $difference[] = $v[0] ?? '';
                                $difference_en[] = $v[1] ?? $v[0];
                            }
                            $skuRow = model('app\index\model\wanlshop\GoodsSku')->where([
                                'goods_id'   => $ids,
                                'difference' => implode(',',$difference),
                            ])->order('createtime desc')->find();


                            if($skuRow){
                                $sku[] = [
                                    'id'           => $skuRow['id'],
                                    'goods_id'     => $ids,
                                    'difference'   => implode(',',$difference),
                                    'difference_en'=> implode(',',$difference_en),
                                    'market_price' => $params['market_price'][$key],
                                    'price'        => $params['price'][$key],
                                    'supply_price' => $params['supply_price'][$key],
                                    'group_price'  => $params['group_price'][$key],
                                    'stock'        => $params['stocks'][$key],
                                    'sort'         => $params['sort'][$key],
                                   // 'rule_id'      => $params['rule_id'][$key],
                                    'rule_id'      => $params['rule_id'],
                                    'weigh'        => $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
                                    'sn'           => $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time(),
                                    'state'        => 0
                                ];
                            }else{
                                $sku[] = [
                                    'goods_id'      => $ids,
                                    'difference'    => implode(',',$difference),
                                    'difference_en' => implode(',',$difference_en),
                                    'market_price'  => $params['market_price'][$key],
                                    'price'         => $params['price'][$key],
                                    'supply_price'  => $params['supply_price'][$key],
                                    'group_price'   => $params['group_price'][$key],
                                    'stock'         => $params['stocks'][$key],
                                    'sort'          => $params['sort'][$key],
                                   // 'rule_id'       => $params['rule_id'][$key],
                                    'rule_id'       => $params['rule_id'],
                                    'weigh'         => $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
                                    'sn'            => $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time(),
                                ];
                            }
                        }
                    }

                    if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
                        $result == false;
                    }
                    $goodsIds = $this->model->where([
                        'parent_id' => $row->id,
                    ])->column('id');
                    foreach ($goodsIds as $goods_id){
                        QueueApi::pricing(['goods_id'=>$goods_id]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    throw $e;
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $ids]);
        $suk = [];
        $goodsSku = [];
        foreach ($skuItem as $vo) {
            $difference = $vo['difference'];
            if($vo['difference'] != $vo['difference_en']){
                $differenceArr = [];
                $diffArr = explode(',',$vo['difference']);
                $diffEnArr = explode(',',$vo['difference_en']);
                foreach ($diffArr as $key => $diff){
                    $differenceArr[] = isset($diffEnArr[$key]) ? $diff . '|' . $diffEnArr[$key] : $diff;
                }
                $difference = implode(',',$differenceArr);
            }

            $suk[] = explode(",", $difference);
            $goodsSku = [
                'price' =>$vo['price'],
                'market_price' =>$vo['market_price'],
                'supply_price' =>$vo['supply_price'],
                'stock' =>$vo['stock'],
                'weigh' =>$vo['weigh'],
                'sn' =>$vo['sn'],
                'rule_id' =>$vo['rule_id'],
                'group_price' => is_array($vo['group_price']) ? $vo['group_price'] : model('app\index\model\wanlshop\GoodsSku')->GroupPrice($vo['group_price'])
            ];
        }
        $spu = [];
        foreach ($spuData as $vo) {

            $spu[] = $vo['name'] == $vo['name_en'] ? $vo['name'] : $vo['name'] .'|'. $vo['name_en'];
        }
        $spuItem = [];
        foreach ($spuData as $vo) {
            $itemArr = explode(",", $vo['item']);
            $itemEnArr = explode(",", $vo['item_en']);
            $item = [] ;
            foreach ($itemArr as $key => $val){
                $item[] = isset($itemEnArr[$key]) ? $val .'|'. $itemEnArr[$key] : $val;
            }
            $spuItem[] = $item;
        }
        $skulist = [];
        foreach ($skuItem as $vo) {
            $difference = $vo['difference'];
            if($vo['difference'] != $vo['difference_en']){
                $differenceArr = [];
                $diffArr = explode(',',$vo['difference']);
                $diffEnArr = explode(',',$vo['difference_en']);
                foreach ($diffArr as $key => $diff){
                    $differenceArr[] = isset($diffEnArr[$key]) ? $diff . '|' . $diffEnArr[$key] : $diff;
                }
                $difference = implode(',',$differenceArr);
            }
            $vo['group_price'] = is_array($vo['group_price']) ? $vo['group_price'] : model('app\index\model\wanlshop\GoodsSku')->GroupPrice($vo['group_price']);
            $skulist[$difference] = $vo;
        }
        $this->assignconfig('spu', $spu);
        $this->assignconfig('spuItem', $spuItem);
        $this->assignconfig('sku', $suk);
        $this->assignconfig('skuItem', $skulist);
        $this->assignconfig('categoryId', $row['category_id']);
        $this->assignconfig('attribute', json_decode($row['category_attribute']));
        $this->view->assign("row", $row);
        $this->assignconfig("row", $row);
        $this->view->assign("goodsSku", $goodsSku);
        $this->assignconfig("goodsSku", $goodsSku);
        $this->view->assign("shop_id", $this->shop->id);
        return $this->view->fetch();
    }


    //更改单字段
    public function field()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $field = $this->request->post('field');
            $id = (int)$this->request->post('id');
            $zhi = $this->request->post('zhi');
            $group_id = (int)$this->request->post('group_id');
            $data = [
                $field=>$zhi
            ];
            $model = model('app\index\model\wanlshop\GoodsSku')
                ->where(['id' =>$id])
                //->allowField(true)
                ->find();
            if(empty($model)){
                $this->error('数据不存在');
            }
            if($field == 'group_price' && $group_id>0){
                $group_price = $model->group_price?:[];
                $group_ar = [];
                foreach ($group_price as &$val){
                    $group_id_id = $val['group_id']??0;
                    if($group_id_id == $group_id){
                        $val['price'] = sprintf("%.2f",$zhi);
                    }
                    $group_ar[] = $val;
                }

                $data = [
                    "group_price"=>json_encode($group_ar)
                ];
            }

            $model->save($data);
            $this->success('操作成功');
        }
    }

    /**
     * 添加类目属性
     */
    public function attribute()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->request("id");
            $list  = model('app\index\model\wanlshop\Attribute')
                ->where('category_id', $id)
                ->select();
            $this->success('查询成功', '', $list);
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }
	/**
	 * 选择链接
	 */
	public function select()
	{
	    if ($this->request->isAjax()) {
	        return $this->index();
	    }
	    return $this->view->fetch();
	}

    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $image = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();
                $sn = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();
                $goods_name = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();
                $goods_sku_name = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();
                $goods_sku_weight = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();
                $goods_sku_price = $currentSheet->getCellByColumnAndRow(9, $currentRow)->getValue();
                $goods_sku_stock = $currentSheet->getCellByColumnAndRow(10, $currentRow)->getValue();
                $goods_sku_supply_price = $currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue();
                $goods_sku_group1_supply_price = $currentSheet->getCellByColumnAndRow(12, $currentRow)->getValue();
                $goods_sku_group2_supply_price = $currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue();
                $goods_sku_group3_supply_price = $currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue();
                $data = [
                    'shop_id' => 0,
                    'title' => $goods_name,
                    'image' => $image,
                    'images' => $image,
                    'price' => $goods_sku_price,
                    'supply_price' => $goods_sku_supply_price,
                    'specs' => $goods_sku_name ? 'multi' : 'single',
                ];
                $this->model = new \app\admin\model\wanlshop\Goods;
                if($this->model->allowField(true)->save($data)){
                    $result = true;
                }
                $group_price[] = [
                    'group_id' => 1,
                    'price' => $goods_sku_group1_supply_price
                ];
                $group_price[] = [
                    'group_id' => 2,
                    'price' => $goods_sku_group2_supply_price
                ];
                $group_price[] = [
                    'group_id' => 3,
                    'price' => $goods_sku_group3_supply_price
                ];
                $sku[] = [
                    'goods_id' 		=> $this->model->id,
                    'difference' 	=> $goods_sku_name ? $goods_sku_name : '默认',
                    'market_price' 	=> $goods_sku_price,
                    'supply_price' 	=> $goods_sku_supply_price,
                    'price' 		=> $goods_sku_price,
                    'stock' 		=> 999,
                    'group_price' 		=> json_encode($group_price),
                    'weigh' 		=> $goods_sku_weight != '' ? bcdiv($goods_sku_weight,1000,2) : 0,
                    'sn' 			=> $sn != '' ? $sn : 'xts_'.time()
                ];
                // 写入SPU
                $spu[] = [
                    'goods_id' => $this->model->id,
                    'name' => '规格',
                    'item' => $goods_sku_name ? $goods_sku_name : '默认',
                ];
            }
            if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
                $result == false;
            }
            if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                $result == false;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }



        $this->success();
    }


    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));

                if ($values) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    if($values && is_array($values) && isset($values['status'])){
                        if($values['status'] == 1){
                            $values['status'] = "normal";
                        }elseif($values['status'] == 0){
                            $values['status'] = "hidden";
                        }
                    }
                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
